package edu.kit.aifb.ruleintegrator.bayes.network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.semanticweb.yars.nx.Resource;

import edu.kit.aifb.ats.triples.TripleRepository;
import edu.kit.aifb.ruleintegrator.repository.RepositoryStatistics;
import edu.kit.aifb.ruleintegrator.rule.Predicate;
import edu.kit.aifb.ruleintegrator.rule.Rule;
import edu.kit.aifb.ruleintegrator.rule.StructureManager;

public class NetworkManager {
	private TripleRepository m_tr;
	
	protected Map<Predicate, RandomVariable> m_predicateVars;
	protected Map<Rule,RandomVariable> m_RuleVars;

	
//	private final MatrixEdgesWithESS m_mustBeAbsentParents;
	private final int NUMBER_OF_INITIAL_RELRULES=1;
	private final int NUMBER_OF_INITIAL_ATTRULES=1;
	private final Network m_network;
	private final RepositoryStatistics m_rs;
	private final StructureManager m_structManager;
	

	public NetworkManager(TripleRepository tr, RepositoryStatistics rs){
		this.m_tr=tr;
		this.m_predicateVars=new HashMap<Predicate, RandomVariable>();
		this.m_RuleVars=new HashMap<Rule,RandomVariable>();

		
		this.m_network=new Network();
		this.m_rs=rs;
		this.m_structManager=new StructureManager(this);
		

	}
	
	public void init() throws IOException{
		
		List<Resource> rels= m_rs.getRelationList();
		for(Resource rel:rels){
				// create a binary-valued variable for each relation
				RandomVariable var=new PredicateVariable(m_structManager.createRelationPredicate(rel),new NoisyOrFactor());
				addVariable(var);
		}
		
		for(Resource cls:m_rs.getClassList()){
			RandomVariable var=new PredicateVariable(m_structManager.createClassPredicate(cls),new NoisyOrFactor());
			addVariable(var);
		}
		
		List<Predicate> metricPredicates=m_structManager.createMetricPredicates();
		
		
		
		
		
	}
	
	protected void addVariable(RandomVariable var){
		if(var instanceof PredicateVariable){
			PredicateVariable predVar=(PredicateVariable)var;
			if(this.m_predicateVars.get(predVar.getPredicate())!=null)
					return;
			this.m_predicateVars.put(predVar.getPredicate(), var);
			this.m_network.addVariable(var);
		}else if(var instanceof RuleVariable)
		{
			RuleVariable ruleVar=(RuleVariable)var;
			if(this.m_RuleVars.get(ruleVar.getRule())!=null)
				return;
			this.m_RuleVars.put(ruleVar.getRule(), var);
			this.m_network.addVariable(var);		
		}
	}
	
	
	
	
	public RepositoryStatistics getRepositoryStatistics()
	{
		return m_rs;
	}
}
